<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8"/>
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>websocket测试</title>
    <meta name="robots" content="all"/>
    <meta name="keywords" content="websocket,测试工具"/>
    <meta name="description" content="websocket,测试工具"/>
    <style>
        .btn-group {
            display: inline-block;
        }

        .output-style {
            overflow: auto;
            border: 1px solid black;
            height: 600px;
            margin: 10px 0;
            position: relative;
        }

        .ul_css {
           position: absolute;
           max-height: 200px; /* 设置最大高度 */
           /*overflow-y: scroll; !* 设置垂直滚动条 *!*/
           background-color: white;
           border: 1px solid black;
           padding: 5px;
           z-index: 9999; /* 设置悬浮框的层级 */
        }

        #output {
            background-color: #c6ddaa
        }


        /*格式化json显示*/
        .bubble {
            white-space: pre;
        }
    </style>
</head>
<body>

<div class="btn-group">
    <input type='text' value='ws://10.0.0.153:8001/gateway' class="form-control"
           style='width:200px;height:30px;display:inline;'
           id='wsaddr' onclick="showHistoryWsAddress()"/>
    <button type="button" class="btn btn-default" onclick='addsocket();'>连接</button>
    <button type="button" class="btn btn-default" onclick='closesocket();'>断开</button>
    <button type="button" class="btn btn-default" onclick='$("#wsaddr").val("")'>清空</button>
</div>
<div id="history-wsaddress" style="display:none;" class="ul_css"></div>

<div class="row">
    <div id="output" class="output-style"></div>
    <!--	<input type="text" id='message' value='{"a":"api","p":"user.Login","d":["wnp001", 0], "rid":"r1"}' class="form-control" style='height:30px;width:810px;' placeholder="待发信息" onkeydown="en(event);">-->

    <!--
        Login: "user*Login
        GetInfo: "user*GetInfo
    -->

    <div>
        <input type="text" id='message' value='{"a":"api","p":"login.login","d":["wnp001",0,{}]}' class="form-control"
               style='height:30px;width:810px;' placeholder="待发信息" onkeydown="en(event);" onclick="showHistoryArgs()">
        <span class="input-group-btn">
            <button class="btn btn-default" type="button" onclick="doSend();">发送</button>
        </span>

    </div>

    <div id="history-messages" style="display:none;" class="ul_css"></div>

</div>
</div>
</body>

<!--<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>-->
<script src="https://code.jquery.com/jquery-1.4.min.js"></script>
<script language="javascript" type="text/javascript">
    var historyList = document.getElementById("history-messages");
    var messageInput = document.getElementById("message");

    var historyListAddress = document.getElementById("history-wsaddress");
    var wsAddressInput = document.getElementById("wsaddr");

    var args_history_key = "args_history_key";
    var wsAddress_history_key = "wsAddress_history_key";

    function getInputHistory(key) {
        return JSON.parse(localStorage.getItem(key)) || []
    }

    function setInputHistory(key, data) {
        if (!data){
            return
        }
        // 获取历史消息列表
        var history = getInputHistory(key);

        if (history.includes(data)){
            return
        }

        // 将当前输入的消息添加到历史消息列表
        history.push(data);

        var newHistory = [];
        for (var i = 0; i < history.length; i++) {
            var v = history[i];
            if (!v) {
                continue
            }
            newHistory.push(v)
        }

        let maxNum = 8;
        if (newHistory.length >= maxNum) {
            newHistory = newHistory.slice(-maxNum)
        }
        newHistory = newHistory.reverse();

        localStorage.setItem(key, JSON.stringify(newHistory))
    }

    // 点击input控件时显示历史消息列表
    function showHistoryWsAddress() {
        if (wsAddressInput.value) {
            return
        }
        // 清空历史消息列表
        historyListAddress.innerHTML = "";
        // 获取历史消息列表
        var history = getInputHistory(wsAddress_history_key);
        [
            "ws://10.0.0.153:8001/gateway",
            "ws://10.0.0.7:8390/gateway",
            "ws://101.35.125.220:6045/gateway",
        ].forEach(item =>{
           if (!history.includes(item)){
               history.push(item)
           }
        });

        if (history.length === 0) {
            history = ["ws://10.0.0.153:8001/gateway", "ws://10.0.0.7:8390/gateway"]
        }
        // 循环添加历史消息列表项
        for (var i = 0; i < history.length; i++) {
            if (!history[i]) {
                continue
            }
            var childDiv = document.createElement("div");
            var label = document.createElement("label");

            label.addEventListener("click", function () {
                wsAddressInput.value = this.textContent;
                historyListAddress.style.display = "none";
            });
            label.textContent = history[i];
            childDiv.appendChild(label);
            historyListAddress.appendChild(childDiv);
        }
        // 显示历史消息列表
        historyListAddress.style.display = "block";
    }

    // 点击input控件时显示历史消息列表
    function showHistoryArgs() {
        if (messageInput.value) {
            return
        }
        // 清空历史消息列表
        historyList.innerHTML = "";
        // 获取历史消息列表
        var history = getInputHistory(args_history_key);
        // 循环添加历史消息列表项
        for (var i = 0; i < history.length; i++) {
            var childDiv = document.createElement("div");
            var label = document.createElement("label");

            label.addEventListener("click", function () {
                messageInput.value = this.textContent;
                historyList.style.display = "none";
            });
            label.textContent = history[i];
            childDiv.appendChild(label);
            historyList.appendChild(childDiv);
        }
        // 显示历史消息列表
        historyList.style.display = "block";
    }

    // 监听input控件的输入事件
    messageInput.addEventListener("input", function () {
        // 隐藏历史消息列表
        historyList.style.display = "none";
        if (!messageInput.value) {
            showHistoryArgs()
        }
    });
    // 监听input控件的失去焦点事件
    messageInput.addEventListener("blur", function () {
        setTimeout(function () {
            // 隐藏历史消息列表
            historyList.style.display = "none";
        }, 200)

    });

    // 监听input控件的输入事件
    wsAddressInput.addEventListener("input", function () {
        // 隐藏历史消息列表
        historyListAddress.style.display = "none";
        if (!wsAddressInput.value) {
            showHistoryWsAddress()
        }
    });
    // 监听input控件的失去焦点事件
    wsAddressInput.addEventListener("blur", function () {
        setTimeout(function () {
            // 隐藏历史消息列表
            historyListAddress.style.display = "none";
        }, 200)

    });

    function formatDate(now) {
        var year = now.getFullYear();
        var month = now.getMonth() + 1;
        var date = now.getDate();
        var hour = now.getHours();
        var minute = now.getMinutes();
        var second = now.getSeconds();
        return year + "-" + (month = month < 10 ? ("0" + month) : month) + "-" + (date = date < 10 ? ("0" + date) : date) +
            " " + (hour = hour < 10 ? ("0" + hour) : hour) + ":" + (minute = minute < 10 ? ("0" + minute) : minute) + ":" + (
                second = second < 10 ? ("0" + second) : second);
    }

    var output;
    var websocket;

    function init() {
        output = document.getElementById("output");
        testWebSocket();
    }

    function addsocket() {
        var wsaddr = $("#wsaddr").val();
        if (wsaddr == '') {
            alert("请填写websocket的地址");
            return false;
        }

        StartWebSocket(wsaddr);
        setInputHistory(wsAddress_history_key, wsaddr);
    }

    function closesocket() {
        websocket.close();
    }

    function StartWebSocket(wsUri) {
        websocket = new WebSocket(wsUri);
        websocket.onopen = function (evt) {
            onOpen(evt)
        };
        websocket.onclose = function (evt) {
            onClose(evt)
        };
        websocket.onmessage = function (evt) {
            onMessage(evt)
        };
        websocket.onerror = function (evt) {
            onError(evt)
        };
    }

    function utf8to16(str) {
        let out, i, len, c;
        let char2, char3;
        out = "";
        len = str.length;
        i = 0;
        while (i < len) {
            c = str.charCodeAt(i++);
            switch (c >> 4) {
                case 0:
                case 1:
                case 2:
                case 3:
                case 4:
                case 5:
                case 6:
                case 7:
                    // 0xxxxxxx
                    out += str.charAt(i - 1);
                    break;
                case 12:
                case 13:
                    // 110x xxxx 10xx xxxx
                    char2 = str.charCodeAt(i++);
                    out += String.fromCharCode(((c & 0x1F) << 6) | (char2 & 0x3F));
                    break;
                case 14:
                    // 1110 xxxx 10xx xxxx 10xx xxxx
                    char2 = str.charCodeAt(i++);
                    char3 = str.charCodeAt(i++);
                    out += String.fromCharCode(((c & 0x0F) << 12) |
                        ((char2 & 0x3F) << 6) |
                        ((char3 & 0x3F) << 0));
                    break;
            }

        }

        return out;

    }


    function onOpen(evt) {
        writeToScreen("<span style='color:red'>连接成功，现在你可以发送信息啦！！！</span>");
    }

    function onClose(evt) {
        writeToScreen("<span style='color:red'>websocket连接已断开!!!</span>");
        websocket.close();
    }

    function onMessage(evt) {
        let _recvData = evt.data
        if (_recvData !== "websocket connect success!") {
            _recvData = JSON.parse(_recvData)
            if (typeof _recvData === "object") {
                _recvData = JSON.stringify(_recvData, null, 2)
            }
        }
        writeToScreen('<span style="color:blue">服务端回应&nbsp;' + formatDate(new Date()) + '</span><br/><span class="bubble">' +
            _recvData + '</span>');
    }

    function onError(evt) {
        writeToScreen('<span style="color: red;">发生错误:</span> ' + evt.data);
    }

    function doSend() {
        var message = $("#message").val();
        if (message == '') {
            alert("请先填写发送信息");
            $("#message").focus();
            return false;
        }
        if (typeof websocket === "undefined") {
            alert("websocket还没有连接，或者连接失败，请检测");
            return false;
        }
        if (websocket.readyState == 3) {
            alert("websocket已经关闭，请重新连接");
            return false;
        }
        console.log(websocket);
        $("#message").val('');
        writeToScreen('<span style="color:green">你发送的信息&nbsp;' + formatDate(new Date()) + '</span><br/>' + message);
        websocket.send(message);

        // 存储历史消息列表
        setInputHistory(args_history_key, message)

    }

    function writeToScreen(message) {
        var div = "<div class='newmessage'>" + message + "</div>";
        // var outputDiv = document.getElementById('output');
        var outputDiv = $("#output");
        outputDiv.append(div);
        outputDiv.scrollTop = outputDiv.scrollHeight
        var diffHeight = outputDiv.attr("scrollHeight") - outputDiv.attr("clientHeight");
        if (diffHeight) {
            outputDiv.attr({
                "scrollTop": diffHeight
            })
        }
    }


    function en(event) {
        var evt = evt ? evt : (window.event ? window.event : null);
        if (evt.keyCode == 13) {
            doSend()
        }
    }
</script>